<script setup lang="ts">
import {get, put, del, post} from "@/axios"
import {computed, onMounted, reactive, ref, toRaw,nextTick} from "vue"

import {ComponentSize, ElMessage} from "element-plus";
import {House, Memo} from "@element-plus/icons-vue";
import RuleInter from "@/type/rule-inter.ts";
import DataType from "@/type/data-type.ts";
import {verifyUserAuthority} from "@/utils/VerifyUserAuthority.ts";

const page = ref(1)
const size = ref(10)
const editOrInsert = ref(false)
const rulePanel = ref(false)
const ruleForm = reactive<RuleInter>({})
const ruleList = reactive([])
const pageInfo = reactive({
  total: 0,
  pageTotal: 0,
})
const ruleDetailsVis = ref(false)
const ruleDetails = ref({
  id: "",
  name: "",
  description: "",
  users: [],
  menus: [],
  dataPermissions:[]
})
const dataList = reactive([])
const activeName = ref()


const ComSize = ref<ComponentSize>('default')
const iconStyle = computed(() => {
  const marginMap = {
    large: '8px',
    default: '6px',
    small: '4px',
  }
  return {
    marginRight: marginMap[ComSize.value] || marginMap.default,
  }
})
const blockMargin = computed(() => {
  const marginMap = {
    large: '32px',
    default: '28px',
    small: '24px',
  }
  return {
    marginTop: marginMap[ComSize.value] || marginMap.default,
  }
})




const reloadRuleList = () => {
  get(`/Rule/GetRules?page=${page.value}&&size=${size.value}`).then((res: any) => {
    pageInfo.total = res.data.totalCount
    pageInfo.pageTotal = res.data.totalPages
    if (page.value == 1) {
      Object.assign(ruleList, res.data.items)
    } else {
      new Promise((resolve) => {
        ruleList.splice(0, ruleList.length)
        resolve(true)
      }).then((e) => {
        if (e) {
          Object.assign(ruleList, res.data.items)
        }
      })
    }
  })
  get("system/data-list").then((res: any) => {
    if (res.status == 200) {
      Object.assign(dataList, res.data)
    }
  })
}
const indexMethod = (index: number) => {
  return index += 1
}


const addRuleFunc = () => {
  editOrInsert.value = true
  rulePanel.value = true
  Object.assign(ruleForm, {
    id: "",
    name: "",
    description: ""
  })
}
const editRuleFunc = (data) => {
  editOrInsert.value = false
  rulePanel.value = true
  Object.assign(ruleForm, data)
}
const deleteRuleFunc = (row: any) => {
  del(`/Rule/DeleteRule?id=${row.id}`).then((res: any) => {
    if (res.status == 200) {
      reloadRuleList()
    }
  })
}

const onSubmit = (type: string) => {
  const rule = toRaw(ruleForm)
  if (editOrInsert.value) {
    post("/Rule/AddRule", rule).then((res: any) => {
      if (res.status === 200) {
        rulePanel.value = false
        reloadRuleList()
      }
    })
  } else {
    put(`/Rule/UpdateRule?id=${rule.id}`, rule).then((res: any) => {
      if (res.status === 200) {
        ElMessage.success("修改成功")
        rulePanel.value = false
        reloadRuleList()
      }
    })
  }
}

const verifyCheck = (data: any) => {
  console.log(ruleList)
  if (ruleForm.dataList) {
    console.log(ruleForm.dataList)
    if (ruleForm.dataList.includes(data.id)) {
      return true
    }
  }
}

const checkRuleFunc = async (row: any) => {
  get(`/Rule/GetRuleDetails?id=${row.id}`).then((res) => {
    if (res.status === 200) {
      ruleDetails.value.id = row.id
      ruleDetails.value.name = row.name
      ruleDetails.value.description = row.description
      ruleDetails.value.users = res.data.users
      ruleDetails.value.menus = res.data.menus
      ruleDetails.value.dataPermissions = res.data.dataPermissions
    }
  })
  await nextTick()
  console.log(ruleDetails)
  ruleDetailsVis.value = true
}

const closeRuleDetailsFunc = () =>{
  Object.assign(ruleDetails.value,{})
  ruleDetailsVis.value = false
}
const clearRuleDataFunc = (row:any) =>{
  verifyUserAuthority().then(res=>{
    if (res){
      del(`/Rule/ClearDataPermission?ruleId=${row.id}`).then((res: any) => {
        if (res.status === 200) {
          reloadRuleList()
        }
      })
    }
  }).catch(()=>{
    ElMessage.error("认证失败")
  })
}
onMounted(() => {
  reloadRuleList()
})
</script>

<template>
  <div class="rule-list-container">
    <div class="rule-table">
      <div class="title">
        <span>角色列表</span>
        <el-button type="success" @click="addRuleFunc">添加角色</el-button>
      </div>
      <el-scrollbar style="width: 100%;" height="500">
        <el-table
            :indent="20"
            :data="ruleList"
            style="width: 100%"
        >
          <el-table-column label="序号" width="60" type="index" :index="indexMethod"/>
          <el-table-column label="角色名称" width="240">
            <template #default="scope">
              <div style="display: flex; align-items: center">
                <el-icon>
                  <Memo/>
                </el-icon>
                <span style="margin-left: 10px">{{ scope.row.name }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="description" label="角色描述" width="280"/>
          <el-table-column width="400">
            <template #default="scope">
              <el-button @click="checkRuleFunc(scope.row)">查看</el-button>
              <el-button type="warning" @click="clearRuleDataFunc(scope.row)">清除数据权限</el-button>
              <el-button type="primary" @click="editRuleFunc(scope.row)">编辑</el-button>
              <el-button type="danger" @click="deleteRuleFunc(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-scrollbar>
      <el-pagination
          v-model:page-size="size"
          background
          hide-on-single-page l
          ayout="prev, pager, next"
          :total="pageInfo.total"
          :page-count="pageInfo.pageTotal"
          v-model:current-page="page"
          @current-change="reloadRuleList"
      />
    </div>
  </div>
  <el-dialog v-model="rulePanel"
             :title="editOrInsert? '新增角色':'编辑角色'" width="800">
    <el-form
        label-position="left"
        :model="ruleForm"
        label-width="auto"
        style="max-width: 600px">
      <el-form-item :required="true" label="角色名称">
        <el-input v-model="ruleForm.name"/>
      </el-form-item>
      <el-form-item label="角色描述">
        <el-input v-model="ruleForm.description"/>
      </el-form-item>
      <el-form-item label="数据权限">
        <div class="data-info">
          <el-checkbox-group v-model="ruleForm.dataList">
            <el-checkbox
                v-for="data in dataList"
                :value="data.id"
                :key="data.id"
                :checked="verifyCheck(data)"
                :label="data.dataType==DataType.User? '用户':
              data.dataType==DataType.Department? '部门'
              :data.dataType==DataType.Rule? '角色':'其他'"
                size="large"/>
          </el-checkbox-group>
        </div>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">提交</el-button>
        <el-button @click="rulePanel = false ">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>


  <el-dialog
      class="user-details"
      v-model="ruleDetailsVis"
      @close="closeRuleDetailsFunc"
      title="角色详情"
      width="900"
  >
    <el-descriptions
        style="margin-top: 5px"
        class="margin-top"
        title="角色信息"
        :column="2"
        :size="ComSize"
        border
    >
      <el-descriptions-item >
        <template #label>
          <div class="cell-item">
            <el-icon :style="iconStyle">
              <tickets />
            </el-icon>
            部门名称：
          </div>
        </template>
        {{ruleDetails.name}}
      </el-descriptions-item>
      <el-descriptions-item >
        <template #label>
          <div class="cell-item">
            <el-icon :style="iconStyle">
              <tickets />
            </el-icon>
            角色描述：
          </div>
        </template>
        {{ruleDetails.description}}
      </el-descriptions-item>
      <el-descriptions-item v-if="ruleDetails.menus">
        <template #label>
          <div class="cell-item">
            <el-icon :style="iconStyle">
              <tickets />
            </el-icon>
            菜单权限：
          </div>
        </template>
        <div class="posts-info">
          <div class="posts" v-for="rule in ruleDetails.menus">
            <el-collapse v-model="activeName" accordion>
              <el-collapse-item :name="rule.menuId">
                <template #title>
                  <el-tag type="success">{{rule.menuName}}</el-tag>
                </template>
                <template #default>
                 <el-icon size="40"><component :is="rule.icon"></component></el-icon> 
                  <p>路径：{{rule.path}}</p>
                  <p>优先级：{{rule.priority}}</p>
                </template>
              </el-collapse-item>
            </el-collapse>
          </div>
        </div>
      </el-descriptions-item>
    </el-descriptions>
    <el-descriptions
        style="margin-top: 5px"
        class="margin-top"
        title="用户信息"
        :column="2"
        :size="ComSize"
        border
    >
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">
            <el-icon :style="iconStyle">
              <tickets />
            </el-icon>
            绑定用户：
          </div>
        </template>
        <div class="posts-info">
          <div class="posts" v-for="user in ruleDetails.users">
            <el-tag type="primary">{{user.username}}</el-tag>
          </div>
        </div>
      </el-descriptions-item>
    </el-descriptions>
    <el-descriptions
        style="margin-top: 5px"
        class="margin-top"
        title="数据权限"
        :column="2"
        :size="ComSize"
        border
    >
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">
            <el-icon :style="iconStyle">
              <tickets />
            </el-icon>
            数据权限：
          </div>
        </template>
        <div class="posts-info">
          <div class="posts" v-for="data in ruleDetails.dataPermissions" :key="data.dataId">
            <el-tag type="primary">{{data.dataType==DataType.User? '用户'
                    :data.dataType==DataType.Department? '部门'
                    :data.dataType==DataType.Rule? '角色':'其他'}}</el-tag>
          </div>
        </div>
      </el-descriptions-item>
    </el-descriptions>
  </el-dialog>
</template>

<style scoped>
.rule-list-container {
  width: 100%;
  padding: 20px;
  display: flex;
  justify-content: center;
}

.rule-table {
  width: 1200px;
  background-color: white;
  font-size: 18px;
}

.title {
  font-size: 20px;
  color: #283443;
  margin: 10px 5px;
  display: flex;
  justify-content: space-between;
}
</style>